package com.example.dao;

import com.example.domain.Post;
import org.apache.ibatis.annotations.*;

import java.util.List;
//帖子的增删改查
public interface PostMapper {

    @Select("SELECT * FROM post WHERE status = 'active' ORDER BY create_time DESC")
    @Results(id = "postMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "title", property = "title"),
            @Result(column = "content", property = "content"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime"),
            @Result(column = "status", property = "status")
    })
    List<Post> findAllRaw();
    //  根据分类和关键词查询
    @Select("<script>" +
            "SELECT * FROM post WHERE status = 'active'" +
            "<if test='categoryId != null'> AND category_id = #{categoryId}</if>" +
            "<if test='keyword != null and keyword != \"\"'> AND (title LIKE CONCAT('%', #{keyword}, '%') OR content LIKE CONCAT('%', #{keyword}, '%'))</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    @ResultMap("postMap")
    List<Post> findByCategoryAndKeyword(@Param("categoryId") Integer categoryId, @Param("keyword") String keyword);
    //  新增
    @Insert("INSERT INTO post (title, content, user_id, category_id, status) VALUES (#{title}, #{content}, #{userId}, #{categoryId}, #{status})")
    void save(Post post);
    //  修改
    @Update("UPDATE post SET title = #{title}, content = #{content}, update_time = CURRENT_TIMESTAMP WHERE id = #{id}")
    void update(Post post);

    @Update("UPDATE post SET status = #{status} WHERE id = #{id}")
    void delete(@Param("id") Integer id);
    //  查询
    @Select("SELECT * FROM post WHERE id = #{id}")
    @ResultMap("postMap")
    Post findById(@Param("id") Integer id);

    @Update("UPDATE post SET status = #{status} WHERE id = #{id}")
    void updateStatus(@Param("id") Integer id, @Param("status") String status);

    @Select("SELECT * FROM post WHERE user_id = #{userId} AND status = 'active' ORDER BY create_time DESC")
    @ResultMap("postMap")
    List<Post> findByUserId(@Param("userId") Integer userId);

    // 新增管理员查询方法
    @Select("<script>" +
            "SELECT * FROM post WHERE 1=1" +
            "<if test='keyword != null and keyword != \"\"'> AND (title LIKE CONCAT('%', #{keyword}, '%') OR content LIKE CONCAT('%', #{keyword}, '%'))</if>" +
            "<if test='status != null and status != \"\"'> AND status = #{status}</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    @ResultMap("postMap")
    List<Post> findAllForAdmin(@Param("keyword") String keyword, @Param("status") String status);
}
